<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>初始化列表 | Daidaini的 个人博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="初始化列表的概念及使用C++98中，标准允许使用花括号”{}”对数组元素进行统一的集合初始值设定。比如： 12int arr[5] &#x3D; &amp;#123;0&amp;#125;;int arr[] &#x3D; &amp;#123;1,2,3,4&amp;#125;;  C++11中，这种初始化的方法，被扩展到了集合（列表）中。 总结初始化方法如下：1） 等号加上赋值表达式，如 int a &#x3D; 3+4；2） 等号 加上花括号的">
<meta property="og:type" content="article">
<meta property="og:title" content="初始化列表">
<meta property="og:url" content="https://daidaini.giteee.io/selfblog/2022/03/23/%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8/index.html">
<meta property="og:site_name" content="Daidaini的 个人博客">
<meta property="og:description" content="初始化列表的概念及使用C++98中，标准允许使用花括号”{}”对数组元素进行统一的集合初始值设定。比如： 12int arr[5] &#x3D; &amp;#123;0&amp;#125;;int arr[] &#x3D; &amp;#123;1,2,3,4&amp;#125;;  C++11中，这种初始化的方法，被扩展到了集合（列表）中。 总结初始化方法如下：1） 等号加上赋值表达式，如 int a &#x3D; 3+4；2） 等号 加上花括号的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-03-23T12:50:22.000Z">
<meta property="article:modified_time" content="2023-02-01T01:52:26.930Z">
<meta property="article:author" content="Daidaini">
<meta property="article:tag" content="C++特性">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/selfblog/atom.xml" title="Daidaini的 个人博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/selfblog/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/selfblog/css/style.css">

  
    
<link rel="stylesheet" href="/selfblog/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 6.3.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/selfblog/" id="logo">Daidaini的 个人博客</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/selfblog/">Home</a>
        
          <a class="main-nav-link" href="/selfblog/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/selfblog/atom.xml" title="RSS 订阅"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="搜索"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://daidaini.giteee.io/selfblog"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-初始化列表" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/selfblog/2022/03/23/%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8/" class="article-date">
  <time class="dt-published" datetime="2022-03-23T12:50:22.000Z" itemprop="datePublished">2022-03-23</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/selfblog/categories/C-%E7%BC%96%E7%A8%8B/">C++编程</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      初始化列表
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="初始化列表的概念及使用"><a href="#初始化列表的概念及使用" class="headerlink" title="初始化列表的概念及使用"></a>初始化列表的概念及使用</h2><p>C++98中，标准允许使用花括号”{}”对数组元素进行统一的集合初始值设定。比如：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">int arr[5] = &#123;0&#125;;</span><br><span class="line">int arr[] = &#123;1,2,3,4&#125;;</span><br></pre></td></tr></table></figure>

<p>C++11中，这种初始化的方法，被扩展到了集合（列表）中。</p>
<p>总结初始化方法如下：<br>1） 等号加上赋值表达式，如 int a &#x3D; 3+4；<br>2） 等号 加上花括号的 初始化列表， 如 int a &#x3D; {3+4};<br>3） 圆括号式的表达式列表（expression list）, 如 int a &#x3D; (3+4);<br>4） 花括号式的初始化列表 ， 如 int a{3+4}</p>
<p>其中，第3、4中方式也可用于获取堆内存 new操作符中，如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">int * i = new int(5);</span><br><span class="line">double *d = new double(1.5f);</span><br></pre></td></tr></table></figure>

<p>标准模板库中容器对初始化列表的支持源自<initializer_list>这个头文件中initialize_list的类模板的支持。<br>只需要包含这个头文件，并且声明一个以initialize_list<T>模板类为参数的构造函数，同样可以使得自定义的类使用列表初始化。</p>
<p>利用初始化列表，重载operator[]，operator&#x3D; 以及使用辅助的数组。例子如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;iostream&gt;</span><br><span class="line">#include &lt;vector&gt;</span><br><span class="line">#include &lt;initializer_list&gt;</span><br><span class="line">using namespace std;</span><br><span class="line"></span><br><span class="line">class Mydata&#123;</span><br><span class="line">public:</span><br><span class="line">    Mydata&amp; operator[](initializer_list&lt;int&gt; l)&#123;</span><br><span class="line">        for(auto i=l.begin();i!=l.end();++i)</span><br><span class="line">            idx.push_back(*i);</span><br><span class="line">       return *this;     </span><br><span class="line">    &#125;</span><br><span class="line">    Mydata&amp; operator=(int v)&#123;</span><br><span class="line">        if(idx.empty()!=true)</span><br><span class="line">        &#123;</span><br><span class="line">            for(auto i = idx.begin();i!=idx.end();++i)</span><br><span class="line">            &#123;</span><br><span class="line">                d.resize((*i&gt;d.size())?*i:d.size());</span><br><span class="line">                d[*i-1] = v;</span><br><span class="line">            &#125;</span><br><span class="line">            idx.clear();</span><br><span class="line">        &#125;</span><br><span class="line">        return *this;</span><br><span class="line">    &#125;</span><br><span class="line">    void print()&#123;</span><br><span class="line">        for(auto i=d.begin();i!=d.end();++i)</span><br><span class="line">            cout&lt;&lt;*i&lt;&lt;&quot; &quot;;</span><br><span class="line">        cout&lt;&lt;endl;    </span><br><span class="line">    &#125;</span><br><span class="line">private:</span><br><span class="line">    vector&lt;int&gt; idx;  //辅助数组，用于记录index</span><br><span class="line">    vector&lt;int&gt; d;    </span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">int main()&#123;</span><br><span class="line">    Mydata d;</span><br><span class="line">    d[&#123;2,3,5&#125;] = 7;   //将第2，3，5位设为7</span><br><span class="line">    d[&#123;1,4,5,8&#125;] = 4; //第1，4，5，8位设为4</span><br><span class="line">    d.print();  //4 7 7 4 7 0 0 4</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此外，初始化列表还可以用于函数返回的情况，但是返回一个初始化列表，通常会导致构造一个临时变量</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">vector&lt;int&gt;Func()&#123;</span><br><span class="line">    return &#123;1,3&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="防止类型收窄"><a href="#防止类型收窄" class="headerlink" title="防止类型收窄"></a>防止类型收窄</h2><p>使用列表初始化还有一个最大优势是 可以防止类型收窄。</p>
<p>类型收窄 一般是指一些可以使得数据变化或者精度丢失的隐式类型转换。</p>
<p>可能导致 类型收窄的典型情况如下：</p>
<ol>
<li><p>以浮点数隐式地转换为整型 比如： int a &#x3D; 1.2</p>
</li>
<li><p>从高精度的浮点数转化为低精度的浮点数，比如： 从long double 隐式地转为 double。或者从double 转为 float。 这种精度降低，都可以视为类型收窄</p>
</li>
<li><p>从整型转为浮点数。如果整型数大到无法使用浮点数精确表达，也可以视为类型收窄</p>
</li>
<li><p>从整型，转为较低长度地整型。 比如：unsigned char &#x3D; 1024; 1024是不能被8位地unsigned char 容纳的</p>
</li>
</ol>
<p>使用初始化列表，是不能容许类型收窄的情况出现的。会编译通不过。</p>
<h2 id="使用自定义初始化列表"><a href="#使用自定义初始化列表" class="headerlink" title="使用自定义初始化列表"></a>使用自定义初始化列表</h2><p>示例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">class Warriors</span><br><span class="line">&#123;</span><br><span class="line">public:</span><br><span class="line">    Warriors(const initializer_list&lt;string&gt;&amp; members)</span><br><span class="line">    &#123;</span><br><span class="line">        for (auto&amp; data : members)</span><br><span class="line">        &#123;</span><br><span class="line">            players.emplace_back(data);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    vector&lt;string&gt; players;</span><br><span class="line"></span><br><span class="line">    void print()</span><br><span class="line">    &#123;</span><br><span class="line">        for (auto itm : players)</span><br><span class="line">            std::cout &lt;&lt; itm &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://daidaini.giteee.io/selfblog/2022/03/23/%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8/" data-id="cldmi24lu0008yhs1a7fyepoi" data-title="初始化列表" class="article-share-link">分享</a>
      
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/selfblog/tags/C-%E7%89%B9%E6%80%A7/" rel="tag">C++特性</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/selfblog/2022/03/23/%E3%80%8ALinux%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%9C%8D%E5%8A%A1%E7%AB%AF%E7%BC%96%E7%A8%8B%E3%80%8B%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">前一篇</strong>
      <div class="article-nav-title">
        
          Linux多线程服务端编程
        
      </div>
    </a>
  
  
    <a href="/selfblog/2021/09/10/%E8%BF%9B%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">后一篇</strong>
      <div class="article-nav-title">进程与线程</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/selfblog/categories/C-11/">C++11</a></li><li class="category-list-item"><a class="category-list-link" href="/selfblog/categories/C-%E7%BC%96%E7%A8%8B/">C++编程</a></li><li class="category-list-item"><a class="category-list-link" href="/selfblog/categories/Linux%E7%B3%BB%E7%BB%9F/">Linux系统</a></li><li class="category-list-item"><a class="category-list-link" href="/selfblog/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a></li><li class="category-list-item"><a class="category-list-link" href="/selfblog/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/selfblog/tags/C-%E5%AD%A6%E4%B9%A0/" rel="tag">C++学习</a></li><li class="tag-list-item"><a class="tag-list-link" href="/selfblog/tags/C-%E6%A0%87%E5%87%86%E5%BA%93/" rel="tag">C++标准库</a></li><li class="tag-list-item"><a class="tag-list-link" href="/selfblog/tags/C-%E7%89%B9%E6%80%A7/" rel="tag">C++特性</a></li><li class="tag-list-item"><a class="tag-list-link" href="/selfblog/tags/C%E8%AF%AD%E8%A8%80/" rel="tag">C语言</a></li><li class="tag-list-item"><a class="tag-list-link" href="/selfblog/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" rel="tag">操作系统</a></li><li class="tag-list-item"><a class="tag-list-link" href="/selfblog/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" rel="tag">数据结构与算法</a></li><li class="tag-list-item"><a class="tag-list-link" href="/selfblog/tags/%E7%AC%94%E8%AE%B0/" rel="tag">笔记</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签云</h3>
    <div class="widget tagcloud">
      <a href="/selfblog/tags/C-%E5%AD%A6%E4%B9%A0/" style="font-size: 10px;">C++学习</a> <a href="/selfblog/tags/C-%E6%A0%87%E5%87%86%E5%BA%93/" style="font-size: 20px;">C++标准库</a> <a href="/selfblog/tags/C-%E7%89%B9%E6%80%A7/" style="font-size: 20px;">C++特性</a> <a href="/selfblog/tags/C%E8%AF%AD%E8%A8%80/" style="font-size: 10px;">C语言</a> <a href="/selfblog/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" style="font-size: 10px;">操作系统</a> <a href="/selfblog/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" style="font-size: 10px;">数据结构与算法</a> <a href="/selfblog/tags/%E7%AC%94%E8%AE%B0/" style="font-size: 20px;">笔记</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/selfblog/archives/2023/02/">二月 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/selfblog/archives/2023/01/">一月 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/selfblog/archives/2022/03/">三月 2022</a></li><li class="archive-list-item"><a class="archive-list-link" href="/selfblog/archives/2021/09/">九月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/selfblog/archives/2021/07/">七月 2021</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/selfblog/2023/02/09/%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0%E7%9A%84%E7%90%86%E8%A7%A3/">回调函数的理解</a>
          </li>
        
          <li>
            <a href="/selfblog/2023/02/07/%E4%BA%8C%E5%88%86%E6%B3%95%E7%9A%84%E7%90%86%E8%A7%A3/">二分法的理解</a>
          </li>
        
          <li>
            <a href="/selfblog/2023/01/31/%E6%8C%87%E9%92%88%E7%9A%84%E7%90%86%E8%A7%A3/">C指针的理解</a>
          </li>
        
          <li>
            <a href="/selfblog/2023/01/31/%E7%90%86%E8%A7%A3CPP%E7%9A%84%E7%A7%BB%E5%8A%A8%E8%AF%AD%E4%B9%89/">理解CPP的移动语义</a>
          </li>
        
          <li>
            <a href="/selfblog/2022/03/23/%E5%B8%B8%E7%94%A8Linux%E5%91%BD%E4%BB%A4/">常用Linux命令</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2023 Daidaini<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/selfblog/" class="mobile-nav-link">Home</a>
  
    <a href="/selfblog/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/selfblog/js/jquery-3.4.1.min.js"></script>



  
<script src="/selfblog/fancybox/jquery.fancybox.min.js"></script>




<script src="/selfblog/js/script.js"></script>





  </div>
</body>
</html>